using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Vin.Event;
using Vin.Tool.AspNetCore.Singleton;

namespace Vin.Tool.AspNetCore.Service;

public abstract class VinEventBackgroundService<T> : BackgroundService where T : VinEventArgs
{
    protected ILogger Logger => VinApp.GetLogger(this.GetType());

    protected bool IsCanRunning;

    public VinEventBackgroundService()
    {
        VinApp.Inject(this);
    }

    protected abstract Task RunAsync(CancellationToken stoppingToken);

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        VinEventManager.Register<T>(OnEventReceived);
        while (!stoppingToken.IsCancellationRequested && !IsCanRunning)
        {
            await Task.Delay(1000);
        }

        await RunAsync(stoppingToken);
    }

    private void OnEventReceived(object? sender, VinEventArgs vinEventArgs) => IsCanRunning = true;
}